package com.cloud.edu.sys.controller;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.edu.contants.UrlConstant;
import com.cloud.edu.request.sys.SysLoginForm;
import com.cloud.edu.sys.model.User;
import com.cloud.edu.sys.service.SysCaptchaService;
import com.cloud.edu.sys.service.SysUserService;
import com.cloud.edu.utils.R;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author dehuisun
 * @date 2018-11-24
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL+"/login")
public class SysLoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysCaptchaService sysCaptchaService;

	/**
	 * 获取验证码
	 * @throws Exception 
	 */
	@GetMapping("/captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws Exception {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
//		User user = sysUserService.queryByUserName(form.getUsername());
		// 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟shiro的拦截地址内．不然后会报空指针
		Subject subject = SecurityUtils.getSubject();
		// 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
		// 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
		// 当以上认证成功后会向下执行,认证失败会抛出异常
		UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
		try {
			//通过Shiro进行用户名密码验证
			subject.login(token);
			
			//将用户登陆信息保存到数据库
			Session session = SecurityUtils.getSubject().getSession();
//			UserLoginLog userLoginLog = new UserLoginLog();
//			userLoginLog.setUserId((String)session.getAttribute("userSessionId"));
//			userLoginLog.setAccountName(loginName);
//			userLoginLog.setLoginIp(session.getHost());
//			userLoginLogService.addUserLoginLog(userLoginLog);
			//登陆成功
			R r =new R();
			return r;
		} catch(UnknownAccountException uae){
			token.clear();
			return R.error("用户未找到");//用户未找到
		} catch(IncorrectCredentialsException ice){
			token.clear();
			return R.error("密码错误");//密码错误
		}catch (LockedAccountException lae) {
			token.clear();
			return R.error("用户已经被锁定");//用户已经被锁定,不能登录
		} catch (ExcessiveAttemptsException e) {
			token.clear();
			return R.error("登录失败次数过多");//登录失败次数过多
		} catch (Exception e){
			token.clear();
			e.printStackTrace();
			return R.error("登录失败");//登录失败次数过多
		}
	}


	/**
	 * 退出
	 */
	@PostMapping("/logout")
	public Map<String, Object> logout() {
		Map<String, Object> map =new HashMap<String, Object>();
//		sysUserTokenService.logout(getUserId());
		return map;
	}
	
}
